package com.seh.contentcenter.controller;

import com.seh.contentcenter.domain.JsonResult;
import com.seh.contentcenter.dto.ChatUserDTO;
import com.seh.contentcenter.dto.MsgDTO;
import com.seh.contentcenter.dto.UserDTO;
import com.seh.contentcenter.entity.Msg;
import com.seh.contentcenter.service.MsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/msg")
public class MsgController {
    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * 保存图片路径，自动从yml文件中获取数据
     */
    @Value("${file-save-path}")
    private String fileSavePath;

    @Autowired
    private MsgService msgService;

    /**
     * 插入一条单聊消息
     *
     * @param msg
     * @return
     */
    @PostMapping("/insertMsg")
    public String insertMsg(@RequestBody Msg msg) {
        String i = msgService.insertMsg(msg);
        return i;
    }

    /**
     * 插入一条图片消息
     *
     * @param fromId
     * @param toId
     * @param msgOrImgType
     * @param sendTime
     * @param files
     * @param request
     * @return
     */
    @PostMapping("/uploadImgMsg")
    public List<JsonResult> uploadMultipleFilesAndContent(@RequestParam("fromId") String fromId,
                                                          @RequestParam("toId") String toId,
                                                          @RequestParam("msgOrImgType") String msgOrImgType,
                                                          @RequestParam("sendTime") String sendTime,
                                                          @RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
        List<JsonResult> results = new ArrayList<>();
        Msg msg = new Msg();
        msg.setFromId(Integer.parseInt(fromId));
        msg.setToId(Integer.parseInt(toId));
        msg.setMsgOrImgType(Integer.parseInt(msgOrImgType));
        msg.setSendTime(sendTime);
        for (MultipartFile file : files) {
            //1.后半段目录：  2020-03-15
            String directory = simpleDateFormat.format(new Date());
            /**
             *  2.文件保存目录  E:/images/2020/03/15/
             *  如果目录不存在，则创建
             */
            File dir = new File(fileSavePath + directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            log.info("图片上传，保存位置：" + fileSavePath + directory);
            //3.给文件重新设置一个名字
            //后缀
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
            //4.创建这个新文件
            File newFile = new File(fileSavePath + directory + "/" + newFileName);
            //5.复制操作
            try {
                file.transferTo(newFile);
                //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/picture_test/" + directory + "/" + newFileName;
                if (msg.getImg() != null) {
                    String picPath = msg.getImg();
                    msg.setImg(picPath + ";" + url);
                } else {
                    msg.setImg(url);
                }
                log.info("图片上传，访问URL:" + url);
                JsonResult result = JsonResult.builder().data(url).message("上传成功!").code("1").build();
                results.add(result);
            } catch (IOException e) {
                JsonResult result = JsonResult.builder().data(null).message("IO异常!").code("-1").build();
                results.add(result);
            }
        }
        //持久化图片消息
        msgService.insertImgMsg(msg);
        return results;
    }


    /**
     * 查询当前用户所有聊天信息
     *
     * @param userId
     */
    @GetMapping("/getMsgList")
    public List<MsgDTO> getMsgList(@RequestParam("userId") Integer userId) {
        return msgService.getMsgList(userId);
    }

    /**
     * 查询指定用户间聊天信息
     *
     * @param fromId
     * @param toId
     * @return
     */
    @GetMapping("/getMsgDetail")
    public List<MsgDTO> getMsgDetail(@RequestParam("fromId") Integer fromId, @RequestParam("toId") Integer toId) {
        return msgService.getMsgDetail(fromId, toId);
    }

    /**
     * 查询当前用户聊天对象
     *
     * @param userId
     * @return
     */
    @GetMapping("/getUserDTO")
    public List<UserDTO> getUserDTO(@RequestParam("userId") Integer userId) {
        return msgService.getUserDTO(userId);
    }

    /**
     * 查询当前用户聊天对象列表（带最后一条回复和日期）
     *
     * @param userId
     * @return
     */
    @GetMapping("/getLastUserDTO")
    public List<ChatUserDTO> getLastUserDTO(@RequestParam("userId") Integer userId) {
        return msgService.getUserDTOWithLastMsg(userId);
    }


}
